import { defineStore } from 'pinia'
import { ref, computed, nextTick } from 'vue'
import type { ThemeMode, ThemeConfig } from '@/types'

export const useThemeStore = defineStore('theme', () => {
  // State
  const mode = ref<ThemeMode>('dark') // Default to dark theme as specified
  const systemTheme = ref<'light' | 'dark'>('dark')
  const config = ref<ThemeConfig>({
    mode: 'dark',
    primaryColor: '#0ea5e9', // Primary blue
    accentColor: '#10b981', // Secondary emerald
    customColors: {
      purple: '#a855f7', // Accent purple
      cyan: '#00bfff',   // Bright cyan from gradient
      emerald: '#00ff88' // Bright emerald from gradient
    }
  })

  // Getters
  const isDark = computed(() => {
    if (mode.value === 'auto') {
      return systemTheme.value === 'dark'
    }
    return mode.value === 'dark'
  })

  const isLight = computed(() => !isDark.value)

  const currentTheme = computed(() => isDark.value ? 'dark' : 'light')

  const themeClasses = computed(() => ({
    'dark': isDark.value,
    'light': isLight.value
  }))

  // Actions
  const setMode = async (newMode: ThemeMode) => {
    mode.value = newMode
    config.value.mode = newMode
    localStorage.setItem('theme_mode', newMode)
    await saveToDatabase()
    applyTheme()
  }

  const toggleTheme = () => {
    const newMode = isDark.value ? 'light' : 'dark'
    setMode(newMode)
  }

  const setSystemTheme = (theme: 'light' | 'dark') => {
    systemTheme.value = theme
    if (mode.value === 'auto') {
      applyTheme()
    }
  }

  const updateConfig = async (newConfig: Partial<ThemeConfig>) => {
    config.value = { ...config.value, ...newConfig }
    localStorage.setItem('theme_config', JSON.stringify(config.value))
    await saveToDatabase()
    applyTheme()
  }

  const setPrimaryColor = async (color: string) => {
    config.value.primaryColor = color
    localStorage.setItem('theme_config', JSON.stringify(config.value))
    await saveToDatabase()
    applyTheme()
  }

  const setAccentColor = async (color: string) => {
    config.value.accentColor = color
    localStorage.setItem('theme_config', JSON.stringify(config.value))
    await saveToDatabase()
    applyTheme()
  }

  // 保存配置到数据库
  const saveToDatabase = async () => {
    try {
      // 动态导入API，避免循环依赖
      const { userAPI } = await import('@/api')
      const { useAuthStore } = await import('@/store/auth')
      const authStore = useAuthStore()
      
      if (authStore.user?.id) {
        await userAPI.saveThemeConfig(authStore.user.id, config.value)
        console.log('✅ 主题配置已保存到数据库')
      }
    } catch (error) {
      console.error('❌ 保存主题配置到数据库失败:', error)
    }
  }

  // 从数据库加载配置
  const loadFromDatabase = async () => {
    try {
      const { userAPI } = await import('@/api')
      const { useAuthStore } = await import('@/store/auth')
      const authStore = useAuthStore()
      
      if (authStore.user?.id) {
        const response = await userAPI.getThemeConfig(authStore.user.id)
        if (response.success && response.data) {
          config.value = { ...config.value, ...response.data }
          mode.value = response.data.mode || 'dark'
          console.log('✅ 从数据库加载主题配置成功:', response.data)
          // 立即应用主题
          await nextTick()
          applyTheme()
          return true
        }
      }
    } catch (error) {
      console.error('❌ 从数据库加载主题配置失败:', error)
    }
    return false
  }

  // 强制刷新主题
  const forceRefresh = () => {
    console.log('🔄 强制刷新主题')
    applyTheme()
    
    // 强制重新编译CSS
    setTimeout(() => {
      const style = document.createElement('style')
      style.textContent = `
        :root {
          --theme-update: ${Date.now()};
        }
      `
      document.head.appendChild(style)
      setTimeout(() => {
        document.head.removeChild(style)
      }, 100)
    }, 100)
  }

  const applyTheme = () => {
    const root = document.documentElement
    const body = document.body

    // Apply dark/light mode
    if (isDark.value) {
      root.classList.add('dark')
      root.classList.remove('light')
      body.classList.add('dark')
      body.classList.remove('light')
    } else {
      root.classList.add('light')
      root.classList.remove('dark')
      body.classList.add('light')
      body.classList.remove('dark')
    }

    // Apply custom CSS variables for colors that can be used in Tailwind
    root.style.setProperty('--color-primary', config.value.primaryColor)
    root.style.setProperty('--color-accent', config.value.accentColor)
    
    // Convert hex colors to RGB values for Tailwind opacity modifiers
    const hexToRgb = (hex: string) => {
      const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
      return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
      } : null
    }
    
    const primaryRgb = hexToRgb(config.value.primaryColor)
    const accentRgb = hexToRgb(config.value.accentColor)
    
    if (primaryRgb) {
      root.style.setProperty('--color-primary-rgb', `${primaryRgb.r}, ${primaryRgb.g}, ${primaryRgb.b}`)
    }
    if (accentRgb) {
      root.style.setProperty('--color-accent-rgb', `${accentRgb.r}, ${accentRgb.g}, ${accentRgb.b}`)
    }

    // 直接覆盖Tailwind的primary和secondary颜色变量
    root.style.setProperty('--tw-color-primary-500', config.value.primaryColor)
    root.style.setProperty('--tw-color-secondary-500', config.value.accentColor)

    // Apply custom colors if any
    if (config.value.customColors) {
      Object.entries(config.value.customColors).forEach(([key, value]) => {
        root.style.setProperty(`--color-${key}`, value)
        const rgb = hexToRgb(value)
        if (rgb) {
          root.style.setProperty(`--color-${key}-rgb`, `${rgb.r}, ${rgb.g}, ${rgb.b}`)
        }
      })
    }

    // Update meta theme-color for mobile browsers
    const metaThemeColor = document.querySelector('meta[name="theme-color"]')
    if (metaThemeColor) {
      metaThemeColor.setAttribute('content', isDark.value ? '#0f172a' : '#ffffff')
    } else {
      const meta = document.createElement('meta')
      meta.name = 'theme-color'
      meta.content = isDark.value ? '#0f172a' : '#ffffff'
      document.head.appendChild(meta)
    }

    // 强制更新所有使用primary和secondary颜色的元素
    console.log('🎨 应用主题配置:', {
      mode: mode.value,
      primaryColor: config.value.primaryColor,
      accentColor: config.value.accentColor,
      customColors: config.value.customColors
    })

    // 动态创建CSS样式来覆盖Tailwind颜色
    const dynamicStyleId = 'dynamic-theme-colors'
    let dynamicStyle = document.getElementById(dynamicStyleId) as HTMLStyleElement
    
    if (!dynamicStyle) {
      dynamicStyle = document.createElement('style')
      dynamicStyle.id = dynamicStyleId
      document.head.appendChild(dynamicStyle)
    }
    
    // 生成动态CSS规则
    const primaryColor = config.value.primaryColor
    const accentColor = config.value.accentColor
    
    dynamicStyle.textContent = `
      /* 动态主题颜色覆盖 */
      .bg-primary-500, .btn-primary { background-color: ${primaryColor} !important; }
      .bg-secondary-500, .btn-secondary { background-color: ${accentColor} !important; }
      .text-primary-500 { color: ${primaryColor} !important; }
      .text-secondary-500 { color: ${accentColor} !important; }
      .text-primary-600 { color: ${primaryColor} !important; filter: brightness(0.9); }
      .text-secondary-600 { color: ${accentColor} !important; filter: brightness(0.9); }
      .text-primary-400 { color: ${primaryColor} !important; filter: brightness(1.2); }
      .text-secondary-400 { color: ${accentColor} !important; filter: brightness(1.2); }
      .border-primary-500 { border-color: ${primaryColor} !important; }
      .border-secondary-500 { border-color: ${accentColor} !important; }
      .hover\\:bg-primary-50:hover { background-color: ${primaryColor}15 !important; }
      .hover\\:bg-secondary-50:hover { background-color: ${accentColor}15 !important; }
      .bg-primary-50 { background-color: ${primaryColor}15 !important; }
      .bg-secondary-50 { background-color: ${accentColor}15 !important; }
      .bg-primary-100 { background-color: ${primaryColor}25 !important; }
      .bg-secondary-100 { background-color: ${accentColor}25 !important; }
      .dark .dark\\:bg-primary-900\\/20 { background-color: ${primaryColor}33 !important; }
      .dark .dark\\:bg-secondary-900\\/20 { background-color: ${accentColor}33 !important; }
      .dark .dark\\:hover\\:bg-primary-900\\/10:hover { background-color: ${primaryColor}1a !important; }
      .dark .dark\\:hover\\:bg-secondary-900\\/10:hover { background-color: ${accentColor}1a !important; }
      .text-primary-700 { color: ${primaryColor} !important; filter: brightness(0.8); }
      .text-secondary-700 { color: ${accentColor} !important; filter: brightness(0.8); }
      .dark .dark\\:text-primary-300 { color: ${primaryColor} !important; filter: brightness(1.3); }
      .dark .dark\\:text-secondary-300 { color: ${accentColor} !important; filter: brightness(1.3); }
      .dark .dark\\:text-primary-400 { color: ${primaryColor} !important; filter: brightness(1.2); }
      .dark .dark\\:text-secondary-400 { color: ${accentColor} !important; filter: brightness(1.2); }
    `
    
    // 触发CSS重新计算
    document.documentElement.style.setProperty('--force-update', Math.random().toString())
    
    // Force re-render by triggering a small style change
    setTimeout(() => {
      body.style.transition = 'background-color 0.3s ease, color 0.3s ease'
      body.style.backgroundColor = isDark.value ? 'rgb(15, 23, 42)' : 'rgb(255, 255, 255)'
    }, 0)
  }

  // AI-driven theme switching
  const switchThemeByTime = () => {
    const hour = new Date().getHours()
    const newMode = (hour >= 6 && hour < 18) ? 'light' : 'dark'
    setMode(newMode)
  }

  const switchThemeByUserActivity = (activityLevel: 'low' | 'medium' | 'high') => {
    // AI logic: High activity = light theme for better visibility
    // Low activity = dark theme for comfort
    const newMode = activityLevel === 'high' ? 'light' : 'dark'
    setMode(newMode)
  }

  const switchThemeByContent = (contentType: 'data' | 'chat' | 'analysis') => {
    // AI logic: Data analysis = light theme for clarity
    // Chat = dark theme for comfort
    // Analysis = based on time of day
    switch (contentType) {
      case 'data':
        setMode('light')
        break
      case 'chat':
        setMode('dark')
        break
      case 'analysis':
        switchThemeByTime()
        break
    }
  }

  const getRecommendedTheme = (): ThemeMode => {
    const hour = new Date().getHours()
    const isWorkingHours = hour >= 9 && hour <= 17
    
    // AI recommendation logic
    if (isWorkingHours) {
      return 'light' // Better for productivity and data reading
    } else {
      return 'dark'  // Better for comfort during off-hours
    }
  }

  // Initialize theme
  const initialize = async () => {
    // 首先尝试从数据库加载配置
    const loadedFromDB = await loadFromDatabase()
    
    if (!loadedFromDB) {
      // 如果数据库加载失败，则从localStorage加载
      const savedMode = localStorage.getItem('theme_mode') as ThemeMode
      if (savedMode) {
        mode.value = savedMode
      }

      const savedConfig = localStorage.getItem('theme_config')
      if (savedConfig) {
        try {
          const parsedConfig = JSON.parse(savedConfig)
          config.value = { ...config.value, ...parsedConfig }
        } catch (err) {
          console.warn('Failed to parse saved theme config:', err)
        }
      }
    }

    // Detect system theme
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    systemTheme.value = mediaQuery.matches ? 'dark' : 'light'

    // Listen for system theme changes
    mediaQuery.addEventListener('change', (e) => {
      setSystemTheme(e.matches ? 'dark' : 'light')
    })

    // Apply initial theme
    applyTheme()
  }

  // Predefined theme presets - 不包含mode，让用户可以在任何明暗模式下使用任何配色
  const presets = {
    default: {
      primaryColor: '#0ea5e9',
      accentColor: '#10b981',
      customColors: {
        purple: '#a855f7',
        cyan: '#00bfff',
        emerald: '#00ff88'
      }
    },
    ocean: {
      primaryColor: '#0891b2',
      accentColor: '#06b6d4',
      customColors: {
        purple: '#8b5cf6',
        cyan: '#22d3ee',
        emerald: '#34d399'
      }
    },
    forest: {
      primaryColor: '#059669',
      accentColor: '#10b981',
      customColors: {
        purple: '#7c3aed',
        cyan: '#06b6d4',
        emerald: '#22c55e'
      }
    },
    sunset: {
      primaryColor: '#f59e0b',
      accentColor: '#f97316',
      customColors: {
        purple: '#c084fc',
        cyan: '#38bdf8',
        emerald: '#4ade80'
      }
    },
    minimal: {
      primaryColor: '#374151',
      accentColor: '#6b7280',
      customColors: {
        purple: '#9333ea',
        cyan: '#0ea5e9',
        emerald: '#059669'
      }
    },
    purple: {
      primaryColor: '#8b5cf6',
      accentColor: '#a855f7',
      customColors: {
        purple: '#c084fc',
        cyan: '#06b6d4',
        emerald: '#10b981'
      }
    },
    rose: {
      primaryColor: '#f43f5e',
      accentColor: '#ec4899',
      customColors: {
        purple: '#a855f7',
        cyan: '#06b6d4',
        emerald: '#10b981'
      }
    },
    amber: {
      primaryColor: '#f59e0b',
      accentColor: '#d97706',
      customColors: {
        purple: '#a855f7',
        cyan: '#06b6d4',
        emerald: '#10b981'
      }
    },
    indigo: {
      primaryColor: '#6366f1',
      accentColor: '#8b5cf6',
      customColors: {
        purple: '#a855f7',
        cyan: '#06b6d4',
        emerald: '#10b981'
      }
    },
    teal: {
      primaryColor: '#14b8a6',
      accentColor: '#0d9488',
      customColors: {
        purple: '#a855f7',
        cyan: '#06b6d4',
        emerald: '#10b981'
      }
    },
    slate: {
      primaryColor: '#64748b',
      accentColor: '#475569',
      customColors: {
        purple: '#a855f7',
        cyan: '#06b6d4',
        emerald: '#10b981'
      }
    },
    emerald: {
      primaryColor: '#10b981',
      accentColor: '#059669',
      customColors: {
        purple: '#a855f7',
        cyan: '#06b6d4',
        emerald: '#34d399'
      }
    }
  }

  const applyPreset = async (presetName: keyof typeof presets) => {
    const preset = presets[presetName]
    if (preset) {
      // 只更新颜色配置，不改变明暗模式
      await updateConfig(preset)
    }
  }

  return {
    // State
    mode,
    systemTheme,
    config,
    
    // Getters
    isDark,
    isLight,
    currentTheme,
    themeClasses,
    
    // Actions
    setMode,
    toggleTheme,
    setSystemTheme,
    updateConfig,
    setPrimaryColor,
    setAccentColor,
    applyTheme,
    
    // Database sync
    saveToDatabase,
    loadFromDatabase,
    forceRefresh,
    
    // AI-driven actions
    switchThemeByTime,
    switchThemeByUserActivity,
    switchThemeByContent,
    getRecommendedTheme,
    
    // Presets
    presets,
    applyPreset,
    
    // Initialization
    initialize
  }
})
